package org.geppeto.eva.synchronizer;

import java.util.ArrayList;
import java.util.Iterator;

public class Semaphore {
	private int _counter;
	private InstanceManager _inst;
	private ArrayList<String> list = new ArrayList<String>();
	
	public Semaphore(InstanceManager inst){
		_counter = 1;
		_inst = inst;
	}

	public Semaphore(InstanceManager inst, int initCounter){
		_counter = initCounter;
		_inst = inst;
	}
	
	protected String acquire(String userID){
		String result="";
		if (_counter >0) {
			_counter--;
			//TODO publish _counter --> ALL
			result = "{\"description\": \"acquired\", " +
					"\"modification\": {\"counter\": \"" +
					Integer.toString(_counter) + "\"}}";
			return result;
		} else {
			list.add(userID);
			//Publish new user in the list --> ALL
			result = "{\"description\": \"added_to_list\", " +
					"\"modification\": {\"added\": \"" + userID + "\", "
					+ "\"list\": \"" + stringifyArrayList2JSON(list)
					+ "\"}}";
			return result;
		}
	}	

	protected String release(String userID){
		String result;
		if (_counter ==0 && !(list.isEmpty()) ) {
			String user = list.get(0);
			list.remove(0);
			//notify user, publish ALL to remove user  
			result = "{\"description\": \"removed_from_list\", " +
					"\"modification\": {\"removed\": \"" + userID + "\", "
					+ "\"list\": \"" + stringifyArrayList2JSON(list)
					+ "\"}}";
			return result;
		} else {
			_counter++;
			//Publish new counter --> ALL
			result = "{\"description\": \"released\", " +
					"\"modification\": {\"counter\": \"" +
					Integer.toString(_counter) + "\"}}";
			return result;
		}
	}	

	protected String getInfo(){
		String result = "";
		String li = stringifyArrayList2JSON(list);
		result += "{mechanism: {\"type\": \"Semaphore\", " +
				"\"counter\": \"" + Integer.toString(_counter) + "\", " +
				"\"list\": " + li + "}}";		
		return result;
	}
	
	protected String getCounter(){
		return Integer.toString(_counter);
	}
	
	private String stringifyArrayList2JSON(ArrayList<String> li){
		//http://www.sigpwned.com/projects/jsonification
		String result="[";
		int i=0;
		Iterator<String> itr = li.iterator();
	    while (itr.hasNext()){	    	
	    	if (i != 0) result+=", ";
	    	result += "\"" + itr.next() + "\"";
	    	i++;
	    }
	    result+="]";
	    return result;
	}
}
